#-*-coding:utf8;-*-
from matplotlib.pyplot import savefig
from numpy import flatiter, left_shift, nan
from numpy.lib.function_base import append
import pandas as pd
import time
import numpy as np
import mplfinance as mpf
import os
import tushare as ts
from  chinese_calendar  import is_holiday
import datetime
from ylTDX import * #from ylTDX import all def function

pd.options.mode.chained_assignment = None #avoid :pandas SettingWithCopyWarning
ts.set_token("6667cd4a2326f2f937062a0f4fb59aea5c56d13b1f6f26225f115fe9")
# M:=55;
# N:=34;
# LC:=REF(CLOSE,1);
# RSI:=((SMA(MAX((CLOSE - LC),0),3,1) / SMA(ABS((CLOSE - LC)),3,1)) * 100);
# FF:=EMA(CLOSE,3);
# MA15:=EMA(CLOSE,21);
# DRAWTEXT(CROSS(85,RSI),75,'▼'),COLORGREEN;
# VAR1:=IF(YEAR>=2038 AND MONTH>=1,0,1);
# VAR2:=REF(LOW,1)*VAR1;
# VAR3:=SMA(ABS(LOW-VAR2),3,1)/SMA(MAX(LOW-VAR2,0),3,1)*100*VAR1;
# VAR4:=EMA(IF(CLOSE*1.3,VAR3*10,VAR3/10),3)*VAR1;
# VAR5:=LLV(LOW,30)*VAR1;
# VAR6:=HHV(VAR4,30)*VAR1;
# VAR7:=IF(MA(CLOSE,58),1,0)*VAR1;
# VAR8:=EMA(IF(LOW<=VAR5,(VAR4+VAR6*2)/2,0),3)/618*VAR7*VAR1;
# 吸筹:IF(VAR8>100,100,VAR8)*VAR1,COLORRED;
# 庄家吸筹:STICKLINE(吸筹>-150,0,吸筹,8,0),COLORRED;
# 散户: 100*(HHV(HIGH,M)-CLOSE)/(HHV(HIGH,M)-LLV(LOW,M)),COLORFFFF00,LINETHICK2;
# RSV:=(CLOSE-LLV(LOW,N))/(HHV(HIGH,N)-LLV(LOW,N))*100;
# K:=SMA(RSV,3,1);
# D:=SMA(K,3,1);
# J:=3*K-2*D;
# 庄家:EMA(J,6),COLORFF00FF,LINETHICK2;
# 第一买点:DRAWTEXT(CROSS(14,吸筹),10, '买1'),COLORYELLOW;
# 第二买点:DRAWTEXT(CROSS(庄家,散户) AND 庄家<50,30, '买2'),COLORRED;
# 第一卖点:DRAWTEXT(CROSS(88,庄家),80, '卖1'),COLORGREEN;
# 第二卖点:DRAWTEXT(CROSS(散户,庄家),60, '卖2'),COLORCYAN;

def xi_chou_check(file_name,code):
    m=54
    n=34                      
    days=60
    pro = ts.pro_api()
    end_date_str=time.strftime("%Y%m%d")
    end_datetime = datetime.datetime.strptime(end_date_str, '%Y%m%d') 
    start_datetime=n_days_before(end_datetime,days)
    start_date_str=start_datetime.strftime("%Y%m%d")
    try:
        df = pro.daily(ts_code='{}.SZ'.format(str(code).zfill(6)), start_date=start_date_str, end_date=end_date_str)       
    except Exception as e:
        print(e)
        time.sleep(60) 
        df = pro.daily(ts_code='{}.SZ'.format(str(code).zfill(6)), start_date=start_date_str, end_date=end_date_str)
    df.set_index('trade_date',inplace=True)
    df.sort_index(inplace=True)   
    df.rename(columns={'vol': 'volume'},inplace=True)  
    df_new=df[["open","high","low","close","volume"]]
    HIGH=df_new["high"].to_list()  
    CLOSE=df_new["close"].to_list()  
    LOW=df_new["low"].to_list()
    Today=time.strftime("%Y-%m-%d-%H-%M-%S")
    YEAR=int(Today.split('-')[0])
    MONTH=int(Today.split('-')[1])
    VAR1=0 if YEAR>=2038 and MONTH>=1 else 1
    VAR2=multiply(REF(LOW,1),VAR1)
    VAR3=multiply(divide(SMA(ABS(subtraction(LOW,VAR2)),3,1),SMA(MAX(subtraction(LOW,VAR2),0),3,1)),100*VAR1)
    VAR4=multiply(EMA([VAR3[i]*10 if CLOSE[i]*1.3 else VAR3[i]/10 for i in range(len(CLOSE))] ,3),VAR1)
    VAR5=multiply(LLV(LOW,30),VAR1)
    VAR6=multiply(HHV(VAR4,30),VAR1)
    VAR7=multiply([1 if i else 0 for i in MA(CLOSE,58)],VAR1)
    VAR8=multiply(EMA([(VAR4[index]+VAR6[index]*2)/2 if i<=j else 0 for index,(i,j)  in enumerate(zip(LOW,VAR5))],3),multiply(divide(VAR7,618),VAR1))
    xi_chou=multiply([100 if i>100 else i for i in VAR8],VAR1)
    first_buy_point=CROSS(14,xi_chou)
    san_hu=divide(multiply(subtraction(HHV(HIGH,m),CLOSE),100),subtraction(HHV(HIGH,m),LLV(LOW,m)))
    rsv=multiply(divide(subtraction(CLOSE,LLV(LOW,n)),subtraction(HHV(HIGH,n),LLV(LOW,n))),100)
    k=SMA(rsv,3,1)
    d=SMA(k,3,1)
    j=subtraction(multiply(k,3),multiply(d,2))
    zhuang_jia=EMA(j,6)
    first_buy_point=CROSS(14,xi_chou)
    second_buy_point=CROSS(zhuang_jia,san_hu)
    first_sell_point=CROSS(88,zhuang_jia)
    second_sell_point=CROSS(san_hu,zhuang_jia)

    output_File = open(file_name,'a+') 
    if len(VAR8)>0:
        output_File.write('{},{},{}\n'.format(str(code).zfill(6),str(round(VAR8[-1],2)),df_new['close'][-1]))
        output_File.flush()
    else:
        output_File.flush()
    return "%s complete"%str(code).zfill(6)

def multi_thread_xi_chou_check(file_name,code_list):
    """
    使用线程池，由系统自动分配线程数量，并打印线程目标函数的返回结果
    """  
    #在append之前先删除原数据表
    import concurrent.futures
    with concurrent.futures.ThreadPoolExecutor() as executor:     
        results=[ executor.submit(xi_chou_check,file_name,i) for i in code_list]
        for f in concurrent.futures.as_completed(results):
            print(f.result())      

if __name__=='__main__':
    path=os.getcwd()
    df=pd.read_csv(path+'/after_process.csv')
    df1=df[["code",'f10']]
    df1.query('f10==True',inplace=True)
    df1.drop(columns=['f10'],inplace=True)
    df1.to_csv("f10_true.csv")
    code_index_list=df1['code'].to_list()
    file_name="{}.csv".format("xi_chou_"+str(time.strftime("%Y_%m_%d_%H")))
    if os.path.exists(file_name): os.remove(file_name)
    output_File = open(file_name,'a+')
    output_File.write('{},{},{}\n'.format('code','var8','close'))
    output_File.flush()
    multi_thread_xi_chou_check(file_name,code_index_list)  
    df_res=pd.read_csv(file_name,encoding='unicode_escape') 
    df_res.columns=['code','var8','close']
    df_res.sort_values(by='var8',ascending=False,inplace=True)
    df_res.to_csv(file_name)